<template>
  <div align="center">
    <el-card>
      <el-steps :active="2" finish-status="finish"  align-center style="margin-bottom: 40px;">
        <el-step title="选择商品分类"></el-step>
        <el-step title="填写商品信息"></el-step>
        <el-step title="填写商品属性"></el-step>
      </el-steps>
      <el-card shadow="hover" style="width:1000px">
        <div style="float:left;width:100px">商品属性</div>
        <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>规格参数组</span>
        </div>
        <!-- specList 为spec的所有数据 展示数据格式为name: agrs -->
       <el-form :model="specForm" label-width="100px" class="demo-ruleForm" size="small">
          <!-- 得到每一行数据和一个下标 -->
          <el-form-item label="模板:">
            <div style="float:left">
              <el-select v-model="selected" placeholder="选择模板之后展示所属规格参数" @change="tempalteChange" clearable>
                <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </div>
          </el-form-item><br/>
          <el-form-item v-for="(item, index) in specList" :key="index" :label="item.name">
              <el-checkbox-group v-model="group[index]">
                    <!-- TODO 数组下标为name的时候只能选中一个 -->
                    <el-checkbox v-for="(item2, index2) in singleOption[index]" :key="index2" :label="item2">{{item2}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item style="float:right">
              <el-button @click="unfold" type="primary">展开</el-button>
            </el-form-item>
        </el-form><br/><br/><br/>
          <!-- table -->
        <el-card>
          <el-table
          border
            :data="propertyData"
            style="width: 100%">
            <el-table-column fixed type="index" width="50"></el-table-column>
            <el-table-column v-for="(col, index) in cols"
                :label="col.label" :key="index" :prop="col.prop" width="120px">
                <template slot-scope="scope">
                    {{scope.row[col.prop]}}
                </template>
              </el-table-column>
            <el-table-column 
                  label="销售价格(单位/分)"
                  width="140">
                  <template slot-scope="scope">
                      <el-input size="small" type="number" min="1000" v-model="scope.row.price" 
                          @input="scope.row.price=scope.row.price.replace(/^(0+)|[^\d]+/g, '')" placeholder="请输入单价"></el-input>
                  </template>
              </el-table-column>
              <el-table-column
                  label="商品库存"
                  width="120">
                  <template slot-scope="scope">
                      <el-input size="small" type="number" min="200" v-model="scope.row.num" 
                          @input="scope.row.num=scope.row.num.replace(/^(0+)|[^\d]+/g, '')" placeholder="请输入商品库存"></el-input>
                  </template>
              </el-table-column>
              <el-table-column
                  label="库存预警值"
                  width="120">
                  <template slot-scope="scope">
                      <el-input size="small" type="number" min="100" v-model="scope.row.alertNum" 
                          @input="scope.row.alertNum=scope.row.alertNum.replace(/^(0+)|[^\d]+/g, '')" placeholder="请输入预警值"></el-input>
                  </template>
              </el-table-column>
              <!-- tmd神经病，插tm的sku编号... -->
              <!-- <el-table-column
                  label="SKU编号"
                  width="120">
                  <template slot-scope="scope">
                      <el-input size="small" type="number" v-model="scope.row.skuId" placeholder="请输入SKU编号"></el-input>
                  </template>
              </el-table-column> -->
              <el-table-column
              label="操作" fixed="right" width="200"> 
                <template slot-scope="scope">
                    &nbsp;&nbsp;<el-button type="danger" size="mini" @click="deleteSingleSpec(scope.$index)">删除</el-button>
                    <el-button size="mini" type="primary" @click="skuImgUpload(scope.$index, scope.row)">点击上传</el-button>
                </template>
              </el-table-column> 
          </el-table>
        </el-card>
        </el-card><br/>
        <!-- 商品参数 -->
        <div style="float:left;width:100px">商品参数</div>
        <el-card>
           <el-table
            :data="goodsParaData"
            style="width: 50%">
            <el-table-column label="参数类型" prop="name">
            </el-table-column>
            <el-table-column
              label="录入参数"
              width="180">
              <template slot-scope="scope">
                  <el-select v-model="tbPara[scope.row.name]">
                    <el-option v-for="(item, index) in scope.row.options" :key="index" :label="item" :value="item"></el-option>
                  </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-card><br/>
       <!--  商品相册 -->
      <div style="float:left;width:100px">商品相册</div>
      <el-card>
         <!-- host是上传到阿里云的n目录 目录结构为/yyyy/MM/dd/host/fileName.png -->
          <el-upload  
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="BASE_API+'/goods/youthOrange/uploadOss/upload/?host=imgsLibrary'"
                class="avatar-uploader">
                <img :src="specForm.image" style="width:300px;height:300px">
            </el-upload>
      </el-card><br/>
      <!-- 详情描述 -->
      <div style="float:left;width:100px">详情描述</div>
      <el-card>
        <tinymce v-model="specForm.details"/>
      </el-card>
     
      </el-card><br/>
         <el-dialog
          title="规格参数图片"
          :visible.sync="skuDialogVisible"
          width="30%"
          :before-close="handleClose">
            <el-upload  
                :show-file-list="false"
                :on-success="skuHandleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="BASE_API+'/goods/youthOrange/uploadOss/upload/?host=imgsLibrary'"
                class="avatar-uploader">
                <img :src="skuImage" style="width:200px;height:200px">
            </el-upload>
          <span slot="footer" class="dialog-footer">
            <el-button @click="skuDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="skuDialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
        <el-button  @click="previous" type="primary" size="small">上一步</el-button>
        <el-button  @click="complete" type="primary" size="small">完成</el-button>
      </el-card>
  </div>
</template>

<script>
import SingleUpload from '../../components/upload/singleUpload'
import tinymce from '@tinymce/tinymce-vue'

export default {
  data () {
    /**
     * Y 标识需要提交的数据
     */
    return {
      BASE_API: 'http://localhost:88/api',
      selected: '', // Y
      C3Id: 0,
      proIndex: 0,
      skuDialogVisible: false,
      skuImage: 'https://orange-youth-bucket.oss-cn-beijing.aliyuncs.com/2020/09/04/Business_images/3f3a37b5-48a8-41b0-8dba-bb23b7084210book1.jpg',
      category3Ids: [], // 1 =》需要提交的表单数据 Y 
      showTbSpuData: {}, // 1
      goodsInfo: {}, // 2 =》需要提交的表单数据 Y
      specList: [], // 获取到规格信息
      specForm: { // Y
        image: 'https://cation-teacher.oss-cn-beijing.aliyuncs.com/2020/08/12/career/929095aa-7e6c-4c78-a913-eae1ef827a4efile.png'
      }, // 3 =》需要提交的表单数据
      singleOption: [], // 存储options切割完的数据
      group: [], // 存储规格参数组[name][red,yellow,bule...] Y
      propertyData: [{}], // 规格参数组的tabdata Y
      cols:[], // 展开添加的动态列
      goodsParaData: [], // 商品参数的表格数据
      tbPara: [], // 用户选中的商品参数val Y
      templateList: [], //模板列表
      array: []
    }
  },
  created () {
    this.goodsPropertyData()
    this.tempalteAndSpec()
    this.getSpecData()
  },
  methods: {
    // 完成
    async complete () {
      var para_items = {},spec_items = {}
      this.propertyData.forEach((item, index) =>{
        // 存储sku的sepc
        // {'颜色': '红色', '版本': '8GB+128GB'}
        item.spec = {}
        // 数据库提交的格式【规格参数】
        // {"颜色":["金色","黑色","蓝色"],"版本":["6GB+64GB"]}
        const obj = {}
        this.cols.forEach((item1, index1) => {
          if(item[item1.prop] !=  undefined){
            const label = item1.label,args = []
            args.push(item[item1.prop])
            obj[label] = args
            item.spec[label] = item[item1.prop]
          }
        })
        spec_items = obj
        item.spec = JSON.stringify(item.spec)
      })

      // 商品参数
      this.goodsParaData.forEach(item =>{
       if (this.tbPara[item.name] != undefined){
         let obj = []
         obj.push(this.tbPara[item.name])
         para_items[item.name] = obj
       }
     })
      const goods = {
        spu: {
          templateId: this.selected, // 模板id
          category1Id: this.category3Ids[0], // 分类id
          category2Id: this.category3Ids[1],
          category3Id: this.category3Ids[2],
          name: this.goodsInfo.name, 
          caption: this.goodsInfo.caption, // 副标题
          brandId: this.goodsInfo.brandId, // 品牌id 
          introduction: this.goodsInfo.introduction, // 介绍
          freightId: this.goodsInfo.freightId, // 运费模板id
          sn: this.goodsInfo.sn, // 货号
          status: 0, // 审核状态
          saleService: JSON.stringify(this.goodsInfo.saleService), // 售后服务
          specItems: JSON.stringify(spec_items), //规格参数
          paraItems: JSON.stringify(para_items), // 参数列表
          image: this.specForm.image, // 图片
          images: this.specForm.images, // img库
          details : this.specForm.details // 详情描述
        },
        skuList: this.propertyData
      }
      console.log(goods, this.tbPara)
      const { data: res } = await this.$http.post(`/goods/spu/add`, goods);
      console.log(res)
      if (res.code == 200) {
        // 跳转审核页面
        this.$message.success("新增成功，待审核")
        this.$router.push({path:'/goods/goods_audit'})
      }
    },
    // 上传图片
    uploadSingleImg () {

    },
    // 规格参数的删除
    deleteSingleSpec (index) {
      this.propertyData.splice(index, 1)
    },
    paraCheckedChange () {
      this.propertyData = []
      this.array = []
    },
    // 商品参数
    async ParaData () {
      const { data: res } = await this.$http.get(`/goods/para/list/${this.selected}`)
      this.goodsParaData = res.data.list
      for (var i = 0; i < this.goodsParaData.length; i++) {
        this.goodsParaData[i].options = this.goodsParaData[i].options.split(',')
      }
    },
    // 根据template去获取这个spec规格参数
    async tempalteAndSpec () {
      const { data: res } = await this.$http.get('/goods/template/list')
      this.templateList = res.data.list
    },
    clearTem () {
      this.specList = [] // 清空初始值
      this.singleOption = [] // checkbox
      this.propertyData = [] // 规格参数-表格数据
      this.group = [] // checkbox-group绑定的model
      this.cols = [] // 用来显示tab的prop和label
    },
    tempalteChange () {
      if( this.selected != '') {
        this.clearTem()
        this.SpecData()
        this.ParaData()
      }else{
        this.clearTem()
      }
    },
    /**
     * 获取规格信息
     * 根据用户选择完模板信息之后，根据id查询数据
     * 所以用户选择完成之后回显的clos的name就为数据库查询的name
     */
    async SpecData () {
      // console.log(this.selected)
      const { data: res } = await this.$http.get(`/goods/spec/specQueryByIdList/${this.selected}`)
      this.specList = res.data.tbSpecs
      for (var x = 0; x < this.specList.length; x++) {
        const option = this.specList[x].options.split(',')
        // 将规格参数存储到这个数组,遍历回显
        this.singleOption.push(option)
        // tab  --- title
        // 追加:如果下标为name则报错 原因： Vue 不允许在已经创建的实例上动态添加新的根级响应式属性
        this.group[x] = []
        // tab表格所需的格式
        let args  = {
          prop: this.specList[x].prop,
          label: this.specList[x].name
        }
        this.cols.push(args)
      }
      // console.log(this.group, this.cols)
    },
    // 计算笛卡尔积
    calcDescartes (array) {
      if (array.length < 2) return array[0] || []
          return [].reduce.call(array, function (col, set) {
              var res = []
              col.forEach(function (c) {
                  set.forEach(function (s) {
                      var t = [].concat(Array.isArray(c) ? c : [c])
                      t.push(s)
                      res.push(t)
                  })
              })
          return res
      })
    },
    // 展开 group 为 选中的checked
    // cols 为 规格参数的name
    unfold () {
      this.paraCheckedChange()
      // 将每项规格参数加入数组中
      this.group.forEach((item) => {
        this.array.push(item)
      })
      // console.log(this.array)
      // console.log(this.cols)
      // 计算笛卡尔积
      this.array = this.calcDescartes(this.array)
      // console.log(this.array)
      for (let i = 0; i < this.array.length; i++) {
          var obj = {}
          for (let j = 0; j < this.array[i].length; j++) {
              // console.log(this.cols[0].prop, this.array[i])
              let prop = this.cols[0].prop
              if( this.cols.length >= 2){
                prop = this.cols[j].prop
                obj[prop] = this.array[i][j] // 为obj设置属性及属性值
              } else {
                obj[prop] = this.array[i]
              }
          }
          this.propertyData.push(obj)
      }
      // console.log(this.propertyData)
    },
    // 上一步回显数据
    previous () {
      this.$router.push({
        path: '/goods/goodsInfo',
        query: {
          index: 3,
          category3Ids: this.category3Ids,
          goodsInfo: encodeURIComponent(JSON.stringify(this.goodsInfo)),
          showTbSpuData: encodeURIComponent(JSON.stringify(this.showTbSpuData))
        }
      })
    },
    // 上传封面之前的函数
    beforeAvatarUpload (file) {
        // 设置允许上传的格式和大小
        const isJPG = file.type === 'image/jpeg'
        // M
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
    },
    // 上传成功的函数
    handleAvatarSuccess (res, file) {
        // response是上传阿里云oss成功后的结果，调用
        // console.log(res,URL.createObjectURL(file.raw)) // 上传响应，base64响应
        this.specForm.image =  res.data.imgUrl
        this.$message.success("success")
    },
    skuImgUpload (index, row) {
      this.skuDialogVisible = true
      this.proIndex = index
    },
    handleClose () {
      this.skuDialogVisible = false
    },
    skuHandleAvatarSuccess (res, file) {
        this.propertyData[this.proIndex].image = res.data.imgUrl
        this.skuImage = res.data.imgUrl
        this.$message.success("success")
    },
    goodsPropertyData () {
      this.category3Ids = this.$route.query.category3Ids // 第一步选择的结果
      this.C3Id = this.category3Ids[this.category3Ids.length-1] // 根据用户的选择进行选中
      this.goodsInfo = JSON.parse(decodeURIComponent(this.$route.query.goodsInfo)) // 第二步输入的信息
      this.showTbSpuData = JSON.parse(decodeURIComponent(this.$route.query.showTbSpuData)) // 商品分类显示的数据
    },
    async getSpecData () {
      // 根据商品分类id去查询模板id,选中默认的
      const { data: res } = await this.$http.get(`/goods/category/categoryQueryTem/${this.C3Id}`)
      // templateId
      this.selected = res.data.temId
      if (this.selected != '' && this.selected != null) {
        this.tempalteChange()
      }
    }
  },
   components: {
    SingleUpload,
    tinymce
  }
}
</script>

<style scoped>

</style>
